package Thread;

import java.util.Random;

public class MultiThreadedArraySum {
    private static final int ARRAY_LENGTH = 10000000;
    private static final Random RANDOM = new Random();
    private static final int[] array = new int[ARRAY_LENGTH];

    public static void main(String[] args) throws InterruptedException {
        // 初始化数组
        for (int i = 0; i < ARRAY_LENGTH; i++) {
            array[i] = RANDOM.nextInt(100) + 1;
        }

        Thread thread1 = new Thread(new SumTask(true));  // 计算偶数下标元素和
        Thread thread2 = new Thread(new SumTask(false)); // 计算奇数下标元素和

        long startTime = System.currentTimeMillis();

        thread1.start();
        thread2.start();

        thread1.join();
        thread2.join();

        long sum = SumTask.evenSum + SumTask.oddSum;
        long endTime = System.currentTimeMillis();

        System.out.println("Sum: " + sum);
        System.out.println("耗时: " + (endTime - startTime) + " milliseconds");
    }

    static class SumTask implements Runnable {
        private static int evenSum = 0;
        private static int oddSum = 0;
        private final boolean isEven;

        SumTask(boolean isEven) {
            this.isEven = isEven;
        }

        @Override
        public void run() {
            int sum = 0;
            for (int i = 0; i < ARRAY_LENGTH; i += 2) {
                if (isEven) {
                    sum += array[i];
                } else {
                    sum += array[i + 1];
                }
            }
            if (isEven) {
                evenSum += sum;
            } else {
                oddSum += sum;
            }
        }
    }
}